from socket import *


class Main_Server:
    def __init__(self, server_socket):
        self.dir = "user.dat"
        self.server_socket = server_socket

    def init(self):
        try:
            with open(self.dir, "w") as file:
                file.write("")
        except:
            pass

    def run(self):
        data = self.server_socket.recvfrom(1024)
        return data[0].decode("utf-8"), data[1]

    def online(self, user):
        try:
            with open(self.dir, "r") as file:
                for i in file.readlines():
                    if f"{user[0]}||{user[1]}::{user[2]}" == i.strip():
                        return
        except:
            pass
        with open(self.dir, "a") as file:
            file.write(f"{user[0]}||{user[1]}::{user[2]}\n")

    def get_user_address(self, userId):
        with open(self.dir, "r") as users:
            for user in users.readlines():
                if user.split("||")[0] == userId:
                    return user.split("||")[1].split("::")
        return None

    def send_massage(self, userId, notice):
        to_user_port = self.get_user_address(userId)
        to_user_port = (to_user_port[0], int(to_user_port[1]))
        notice = f"{userId}::{notice}".encode("utf-8")
        # print(notice.decode("utf-8"), to_user_port)
        self.server_socket.sendto(notice, to_user_port)


if __name__ == "__main__":
    socket_server = socket(AF_INET, SOCK_DGRAM)
    socket_server.bind(("", 9999))
    server = Main_Server(socket_server)
    server.init()

    while True:
        return_data = server.run()
        if return_data[0].split("||")[0] == "online":
            server.online(return_data[0].split("||")[1].split("::"))
            print("%s已上线" % return_data[0].split("||")[1].split("::")[0])
        elif return_data[0].split("||")[0] == "send_massage":
            return_data = return_data[0].split("||")[1].split("::")
            userId = return_data[0]
            notice = return_data[1]
            server.send_massage(userId, notice)
